// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: Apache-2.0

import { Any } from "$lib/api/proto/google/protobuf/any";
import { NewMsgNotice } from "$lib/api/proto/notices_user";
import { PullNoticeResponse_CODE } from "$lib/api/proto/user_api";
import { appStore } from "./app.svelte";
import { userStore } from "./user.svelte";


export class NoticeStore {
    private unlistenFn: (() => void) | null = null;

    async init() {
        while (userStore.userSession != null) {
            await this.pullNotice(userStore.userSession);
        }
    }

    private async pullNotice(sessionId: string) {
        if (this.unlistenFn != null) {
            this.unlistenFn();
            this.unlistenFn = null;
        }

        const resp = appStore.userApiClient.pullNotice({
            sessionId: sessionId,
        });
        this.unlistenFn = resp.responses.onMessage(msg => {
            if (msg.code != PullNoticeResponse_CODE.CODE_OK) {
                appStore.addToastMessage({
                    level: 'error',
                    content: msg.errMsg,
                    keepTime: 2000
                });
            } else {
                if (msg.noticeData != undefined) {
                    this.processNotice(msg.noticeData);
                }
            }
        });
        await resp;
    }

    private async processNotice(noticeData: Any) {
        if (Any.contains(noticeData, NewMsgNotice)) {
            await userStore.syncUnReadMsgCount();
        }
    }
}

export const noticeStore = $state(new NoticeStore());